package cn.doitedu.zk.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

/**
 * @date: 2019/7/8
 * @site: www.doitedu.cn
 * @author: hunter.d 涛哥
 * @qq: 657270652
 * @description: zookeeper的监听机制示例代码
 */
public class WatchDemo {


    ZooKeeper zk = null;

    @Before
    public void init() throws Exception {
        zk = new ZooKeeper("spark01:2181,spark02:2181,spark03:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath()); // 事件发生的节点路径
                System.out.println(event.getState()); // 事件发生时，客户端的连接状态
                System.out.println(event.getType()); // 事件的类型

            }
        });
    }


    /**
     * 方式 1：  在注册监听时，传入boolean参数，那么事件的回调逻辑 用 构造zk客户端时传入的回调逻辑
     * @throws Exception
     */
    @Test
    public void testWatchDataChanged() throws Exception {

        byte[] data = zk.getData("/abc", true, null);  // zk对象是一个多线程的工作逻辑，对事件通知的监听，是开启了一个另外的线程在工作

        Thread.sleep(Long.MAX_VALUE);
    }


    /**
     * 方式 2：  在注册监听时，传入Watcher对象，那么事件的回调逻辑 用 此处传入的watcher
     * @throws Exception
     */
    @Test
    public void testWatchDataChanged2() throws Exception {

        byte[] data = zk.getData("/abc", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("哈哈哈哈哈, 我来也");

            }
        },null);

        Thread.sleep(Long.MAX_VALUE);
    }


    /**
     * 监听 节点的子节点增减事件
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testWatchNodeChildrenChanged() throws KeeperException, InterruptedException {

        zk.getChildren("/abc", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath()); // 事件发生的节点路径
                System.out.println(event.getType()); // 事件的类型
            }
        });

        Thread.sleep(Long.MAX_VALUE);

    }



    /**
     * 监听 节点被创建或被删除的事件
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testWatchStat() throws KeeperException, InterruptedException {

        zk.exists("/bbb",true);

        Thread.sleep(Long.MAX_VALUE);
    }




}
